# -*- coding: utf-8 -*-
import math

from flask import Blueprint, request, jsonify, json, Response
from flask_cors.core import LOG
from sqlalchemy import func, alias

from application import db
from common.models.article_category import ArticleCategory
import uuid
from common.libs.queryToDict import *
from werkzeug.utils import secure_filename
from common.models.article import Article
from common.models.user import User

from common.models.article_category_mapping import ArticleCategoryMapping
from common.models.article_category_tree import article_category_tree
from config.base_setting import IMG_PATH
from operator import and_, __or__, or_, __and__
import os

route_article_category = Blueprint('route_article_category', __name__)


# 获取文章类型列表信息
@route_article_category.route("/get_article_category_list", methods=["GET", "POST"])
def get_article_category_list():
    resp = {"err": "0", "errMsg": "", "data": ""}
    article_category = ArticleCategory()
    in_vo = request.get_json()
    filter = []
    # 一页多少条
    page_size = in_vo["page_size"]
    # 第几页
    page_index = in_vo["page_index"]
    filter.append(ArticleCategory.flag == "0")

    # 所属用户
    # if "user_id" in in_vo:
        # article_category.user_id = in_vo["user_id"]
        # filter.append(ArticleCategory.user_id == article_category.user_id)

    # 根据用户权限查看的数据不同
    if "user_id" in in_vo:
        user_id = in_vo["user_id"]
        user = User.query.filter(User.user_Id == user_id).first()
        if user.user_type == "2":
            if in_vo and "article_category_model" in in_vo:
                article_category.article_category_model = in_vo["article_category_model"]
                filter.append(__or__(ArticleCategory.user_id == user_id,
                                     ArticleCategory.article_category_model == article_category.article_category_model))
            else:
                filter.append(ArticleCategory.user_id == user_id)

        elif user.user_type == "3":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category.article_category_model = in_vo["article_category_model"]
                filter.append(__or__)
    else:
        # 隐私权限
        if in_vo and "article_category_model" in in_vo:
            article_category.article_category_model = in_vo["article_category_model"]
            filter.append(ArticleCategory.article_category_model == article_category.article_category_model)

    # res_list = ArticleCategory.query.filter(*filter).limit(
    #     page_size).offset(
    #     (page_index - 1) * page_size).all()
    paginates = ArticleCategory.query.filter(*filter).order_by(ArticleCategory.create_time.desc()).paginate(page_index,
                                                                                                            page_size,
                                                                                                            error_out=False)
    items = paginates.items
    # total为总页面数
    total = math.ceil(paginates.total)
    if items:
        resp["data"] = query_to_dict(items)
        resp["total"] = total
    return jsonify(resp)


#  取得所有文章类型
@route_article_category.route("/get_article_category_all_list", methods=["GET", "POST"])
def get_article_category_all_list():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    filter = []
    filter.append(ArticleCategory.flag == "0")
    filter.append(ArticleCategory.type.like("0"))
    # 根据用户权限查看的数据不同
    if in_vo and "user_id" in in_vo:
        user_id = in_vo["user_id"]
        user = User.query.filter(User.user_Id == user_id).first()
        if user.user_type == "2":
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(__or__(ArticleCategory.user_id == user_id,
                                     ArticleCategory.article_category_model.like("%" + article_category_model + '%')))
            else:
                filter.append(ArticleCategory.user_id == user_id)
        elif user.user_type == "3":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(ArticleCategory.article_category_model.like("%" + article_category_model + '%'))
    else:
        # 隐私权限
        if in_vo and "article_category_model" in in_vo:
            article_category_model = in_vo["article_category_model"]
            filter.append(ArticleCategory.article_category_model.like("%" + article_category_model + '%'))

    res_list = ArticleCategory.query.with_entities(ArticleCategory.article_category_id,
                                                   ArticleCategory.article_category_pid,
                                                   ArticleCategory.user_id,
                                                   ArticleCategory.title,
                                                   ArticleCategory.content,
                                                   ArticleCategory.summary,
                                                   ArticleCategory.style,
                                                   ArticleCategory.type,
                                                   ArticleCategory.icon,
                                                   ArticleCategory.count,
                                                   ArticleCategory.order_number,
                                                   ArticleCategory.flag,
                                                   ArticleCategory.meta_keywords,
                                                   ArticleCategory.meta_description,
                                                   ArticleCategory.remarks,
                                                   ArticleCategory.category_id,
                                                   func.count(ArticleCategoryMapping.article_id).label(
                                                       "article_count")).outerjoin(
        ArticleCategoryMapping,
        ArticleCategoryMapping.category_id == ArticleCategory.article_category_id).filter(*filter).group_by(
        ArticleCategory.article_category_id).all()
    if res_list:
        resp["data"] = query_to_dict(res_list)
    else:
        resp["err"] = "1"

    return jsonify(resp)


#  取得所有文章第一层章节
@route_article_category.route("/get_article_category_all_1_list", methods=["GET", "POST"])
def get_article_category_all_1_list():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    filter = []
    filter.append(ArticleCategory.flag == "0")
    filter.append(ArticleCategory.type == "1")
    filter.append(ArticleCategory.article_category_pid == None)

    # 根据用户权限查看的数据不同
    if "user_id" in in_vo:
        user_id = in_vo["user_id"]
        user = User.query.filter(User.user_Id == user_id).first()
        if user.user_type == "2":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(__or__(ArticleCategory.user_id == user_id,
                                     ArticleCategory.article_category_model.like("%" + article_category_model + '%')))
            else:
                filter.append(ArticleCategory.user_id == user_id)

        elif user.user_type == "3":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(ArticleCategory.article_category_model == article_category_model)
    else:
        # 隐私权限
        if in_vo and "article_category_model" in in_vo:
            article_category_model = in_vo["article_category_model"]
            filter.append(ArticleCategory.article_category_model == article_category_model)

    res_list = ArticleCategory.query.with_entities(ArticleCategory.article_category_id,
                                                   ArticleCategory.article_category_pid,
                                                   ArticleCategory.user_id,
                                                   ArticleCategory.title,
                                                   ArticleCategory.content,
                                                   ArticleCategory.summary,
                                                   ArticleCategory.style,
                                                   ArticleCategory.type,
                                                   ArticleCategory.icon,
                                                   ArticleCategory.count,
                                                   ArticleCategory.order_number,
                                                   ArticleCategory.flag,
                                                   ArticleCategory.category_id,
                                                   ArticleCategory.meta_keywords,
                                                   ArticleCategory.meta_description,
                                                   ArticleCategory.remarks,
                                                   func.count(Article.article_id).label(
                                                       "article_count")).outerjoin(
        Article,
        Article.article_sub_categorys.ilike('%' + ArticleCategory.article_category_id + '%')).filter(*filter).group_by(
        ArticleCategory.article_category_id).all()
    if res_list:
        resp["data"] = query_to_dict(res_list)
    else:
        resp["err"] = "1"

    return jsonify(resp)


#  取得所有文章章节树
@route_article_category.route("/get_article_category_tree_all_list", methods=["GET", "POST"])
def get_article_category_tree_all_list():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    filter = []
    filter.append(ArticleCategory.flag == "0")
    filter.append(ArticleCategory.type == "1")

    # 根据用户权限查看的数据不同
    if "user_id" in in_vo:
        user_id = in_vo["user_id"]
        user = User.query.filter(User.user_Id == user_id).first()
        if user.user_type == "2":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(__or__(ArticleCategory.user_id == user_id,
                                     ArticleCategory.article_category_model.like("%" + article_category_model + '%')))
            else:
                filter.append(ArticleCategory.user_id == user_id)

        elif user.user_type == "3":
            # 隐私权限
            if in_vo and "article_category_model" in in_vo:
                article_category_model = in_vo["article_category_model"]
                filter.append(ArticleCategory.article_category_model == article_category_model)
    else:
        # 隐私权限
        if in_vo and "article_category_model" in in_vo:
            article_category_model = in_vo["article_category_model"]
            filter.append(ArticleCategory.article_category_model == article_category_model)
    category = alias(ArticleCategory)
    res_list = ArticleCategory.query.with_entities(ArticleCategory.article_category_id,
                                                   ArticleCategory.article_category_pid,
                                                   ArticleCategory.user_id,
                                                   ArticleCategory.title,
                                                   ArticleCategory.content,
                                                   ArticleCategory.summary,
                                                   ArticleCategory.style,
                                                   ArticleCategory.type,
                                                   ArticleCategory.icon,
                                                   ArticleCategory.count,
                                                   ArticleCategory.order_number,
                                                   ArticleCategory.flag,
                                                   ArticleCategory.meta_keywords,
                                                   ArticleCategory.meta_description,
                                                   ArticleCategory.remarks,
                                                   ArticleCategory.category_id,
                                                   ArticleCategory.article_category_model,
                                                   category.c.title.label("category_title")).outerjoin(
        category,
        category.c.article_category_id == ArticleCategory.category_id).filter(*filter).all()

    # res_list = ArticleCategory.query.filter(__and__(ArticleCategory.type.like("1"), ArticleCategory.flag == "0")).all()
    article_category_list = []
    for article_category in res_list:
        if article_category.article_category_pid is None:
            article_category_tree_item = query_to_dict(article_category)
            article_category_tree_item["label"] = article_category.title
            article_category_tree_item["value"] = article_category.article_category_id
            article_category_tree_item["children"] = tree(article_category.article_category_id, res_list)
            article_category_list.append(article_category_tree_item)

    if article_category_list:
        resp["data"] = article_category_list
    else:
        resp["err"] = "1"
    return jsonify(resp)


# 生成树
def tree(article_category_id, article_category_list):
    sub_article_category = []
    try:
        for entity in article_category_list:
            if entity.article_category_pid is not None and entity.article_category_pid == article_category_id:
                sub_article_category.append(entity)

        sub_result_list = []
        for sub in sub_article_category:
            result_item = query_to_dict(sub)
            result_param = tree(sub.article_category_id, article_category_list)
            if len(result_param):
                result_item["children"] = result_param
            result_item["label"] = sub.title
            result_item["value"] = sub.article_category_id
            sub_result_list.append(result_item)
        return sub_result_list
    except Exception as e:
        LOG.exception('error query_sub_menu_info !')
    raise e


# 上传图片
@route_article_category.route("/upload", methods=["GET", "POST"])
def upload():
    resp = {"code": "200", "errMsg": "",
            "data": {"url": ""}}
    http_url_path = IMG_PATH  # "http://127.0.0.1:8999/"
    # 文件对象保存在request.files上，并且通过前端的input标签的name属性来获取
    fp = request.files.get("img")

    base_path = os.path.dirname(__file__)  # 当前文件所在路径
    http_url = os.path.join(http_url_path, 'static', secure_filename(fp.filename))
    resp["data"]["url"] = http_url
    # upload_path = os.path.join(base_path, 'static/images', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    upload_path = os.path.join('web/static', secure_filename(fp.filename))  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
    # 保存文件到服务器本地
    fp.save(upload_path)
    return jsonify(resp)


# 根据id获取文章类型信息
@route_article_category.route("/select_article_category", methods=["GET", "POST"])
def select_article_category():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    # 文章Id
    article_id = "" if in_vo["article_id"] is None else in_vo["article_id"]

    res_list = ArticleCategory.query.filter(ArticleCategory.article_id == article_id).first()
    resp["data"] = query_to_dict(res_list)
    return jsonify(resp)


# 添加文章类型
@route_article_category.route("/insert_article_category", methods=["GET", "POST"])
def insert_article_category():
    in_vo = request.get_json()
    article_category = ArticleCategory()
    article_category.article_category_id = uuid.uuid4()
    if "article_category_pid" in in_vo:
        article_category.article_category_pid = in_vo["article_category_pid"]
    article_category.title = in_vo["title"]

    if "user_id" in in_vo:
        article_category.user_id = in_vo["user_id"]

    if "category_id" in in_vo:
        article_category.category_id = in_vo["category_id"]
    if "content" in in_vo:
        article_category.content = in_vo["content"]
    if "type" in in_vo:
        article_category.type = in_vo["type"]

    if "icon" in in_vo:
        article_category.icon = in_vo["icon"]

    if "article_category_model" in in_vo:
        article_category.article_category_model = in_vo["article_category_model"]

    if "summary" in in_vo:
        article_category.meta_keywords = in_vo["summary"]
        article_category.article_model = in_vo["summary"]
        article_category.summary = in_vo["summary"]
    if "order_number" in in_vo:
        article_category.order_number = in_vo["order_number"]
    article_category.flag = "0"
    db.session.add(article_category)
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


# 物理删除文章类型
@route_article_category.route("/update_delete_article_category", methods=["GET", "POST"])
def update_delete_article_category():
    resp = {"err": "0", "errMsg": "", "data": ""}
    in_vo = request.get_json()
    article_category_id = in_vo["article_category_id"]
    article_category = ArticleCategory.query.filter(ArticleCategory.article_category_id == article_category_id).first()
    # article_category.flag = "1"
    db.session.delete(article_category)
    db.session.commit()
    resp = {"err": "0", "errMsg": "", "data": ""}
    return jsonify(resp)


# 更新文章类型
@route_article_category.route("/update_article_category", methods=["GET", "POST"])
def update_article():
    in_vo = request.get_json()
    article_category_id = in_vo["article_category_id"]
    article_category = ArticleCategory.query.filter(ArticleCategory.article_category_id == article_category_id).first()

    if article_category:
        if "title" in in_vo:
            article_category.title = in_vo["title"]
        if "content" in in_vo:
            article_category.content = in_vo["content"]

        if "article_category_model" in in_vo:
            article_category.article_category_model = in_vo["article_category_model"]

        if "user_id" in in_vo:
            article_category.user_id = in_vo["user_id"]

        if "icon" in in_vo:
            article_category.icon = in_vo["icon"]

        if "category_id" in in_vo:
            article_category.category_id = in_vo["category_id"]
        if "summary" in in_vo:
            article_category.meta_keywords = in_vo["summary"]
            article_category.article_model = in_vo["summary"]
            article_category.summary = in_vo["summary"]
        if "order_number" in in_vo:
            article_category.order_number = in_vo["order_number"]
        db.session.commit()
        resp = {"err": "0", "errMsg": "", "data": ""}
    else:
        resp = {"err": "1", "errMsg": "更新失败,未找到更新数据!", "data": ""}
    return jsonify(resp)
